import { transform } from "ol/proj";
import { View } from "ol";

/**
 * @abstract 用于设置地图的投影
 * @param {*} map 地图实例
 * @param { 'EPSG:4326' | 'EPSG:3857' } projection  投影类型
 * @returns
 */
export const setProjection = (map, projection) => {
  const currentProjection = map.getView().getProjection().getCode();

  if (currentProjection == projection) return;

  const viewProperties = map.getView().getProperties();

  viewProperties.projection = projection;
  viewProperties.center = transform(
    viewProperties.center,
    currentProjection,
    projection
  );

  map.setView(new View(viewProperties));
};

/**
 *  @abstract 获取地图的缩放级别
 * @param {*} map
 * @returns {number} 缩放级别(整数)
 */
export const getZoom = map => {
  return Math.floor(map.getView().getZoom());
};

/**
 * @abstract 获取地图的当前范围
 */
export const getExtent = map => {
  return map.getView().calculateExtent(map.getSize());
};

/**
 * @abstract 简易的飞行方法
 * @param {*} map
 * @param {*} param1
 * @param {*} param1.position 目标位置
 * @param {*} param1.zoom 目标缩放级别
 * @param {*} param1.duration 飞行时间
 * @param {*} callback 回调函数
 */
export function flyTo(map, { position, zoom = 11, duration = 1000 }) {
  //这里给动画设置一个初始值
  map.getView().animate({
    //将地理坐标转为投影坐标
    center: position,
    duration: duration,
    zoom: zoom,
  });
}

/**
 *  @abstract 飞行到指定要素
 * @param {*} map
 * @param {*} feature 希望飞行到的要素
 * @param {*} duration  飞行时间
 */
export const flyToFeature = (map, feature, duration = 1000) => {
  map.getView().fit(feature.getGeometry(), {
    padding: [50, 50, 50, 50],
    duration,
  });
};
